import { Routes, Route, Navigate } from 'react-router-dom';
import Ceecs from "./pages/ceecs/Ceecs";
import Admin from "./pages/admin/Admin";
import { Modal, Image, AutoCenter, Button } from 'antd-mobile';
import { useState, useEffect, useCallback } from 'react';
import AuthContext from './auth/AuthContext';
import axios from 'axios';

function App() {
  const [me, setMe] = useState(null);
  const [code, setCode] = useState(null);
  const [hasFirstFetchMe, setHasFirstFetchMe] = useState(false);
  const [woaQrCode, setWoaQrCode] = useState(null);
  const [isinwechat, setIsinwechat] = useState(false);
  const fetchMe = useCallback(
    async () => {
      const { data: { data } } = await axios.get('/me', { params: { woa_qrcode_scene_id: code } });
      return data;
    },
    [code],
  )
  useEffect(() => {
    let interval;
    let fetchMe_ = async () => {
      if (!me) {
        let data = await fetchMe();
        if (data) {
          setMe(data);
          clearInterval(interval);
        }
        setHasFirstFetchMe(true);
      }
    }
    fetchMe_();
    interval = setInterval(fetchMe_, 3000);
    return () => clearInterval(interval);
  }, [fetchMe, me]);
  useEffect(() => {
    if (!me && hasFirstFetchMe) {
      async function fetchWoaQrCode() {
        const { data: { data, code, isinwechat } } = await axios.get('/woa_qrcode');
        setWoaQrCode(data);
        setCode(code);
        setIsinwechat(isinwechat);
      }
      fetchWoaQrCode();
    }
  }, [me, hasFirstFetchMe]);
  return (
    <div className="App">
      <AuthContext.Provider value={{ me }}>
        {
          !me && <Modal
            visible={true}
            transparent
            maskClosable={false}
            title={isinwechat ? '' : `微信授权登录${woaQrCode ? "" : "中。。。"}`}
            content={
              isinwechat ?
                (
                  <AutoCenter>
                    <Button onClick={() => window.location.href = woaQrCode}>点击微信授权</Button>
                  </AutoCenter>
                ) :
                (
                  woaQrCode ?
                    <AutoCenter>
                      <Image src={woaQrCode} width={300} />
                      <div style={{ textAlign: "center" }}>关注公众号登录</div>
                    </AutoCenter> :
                    <></>
                )
            }
          >
          </Modal>
        }
        <Routes>
          <Route path="/" element={<Navigate to="/ceecs" />} />
          <Route path="/ceecs" element={<Ceecs />} />
          {/* <Route path="/admin" element={<Admin />} /> */}
        </Routes>
      </AuthContext.Provider>
    </div >
  );
}

export default App;

